package email

import (
	"fmt"
	"log"
	"net/smtp"
	"strings"

	"gitee.com/dayu1985/framework/context"
)

type MailService struct {
	Host     string
	Email    string
	Account  string
	Password string
}

type Email struct {
	To      []string
	Title   string
	Content string
}

func NewMailService(cfg *context.Configuration) (*MailService, error) {

	service := MailService{}
	var err error

	service.Host, err = cfg.INI.GetValue("email", "host")

	if err != nil {
		return nil, err
	}

	service.Email, err = cfg.INI.GetValue("email", "email")

	if err != nil {
		return nil, err
	}

	service.Account, err = cfg.INI.GetValue("email", "account")

	if err != nil {
		return nil, err
	}

	service.Password, err = cfg.INI.GetValue("email", "password")

	if err != nil {
		return nil, err
	}

	return &service, nil
}

func NewEmail(to []string, title, content string) *Email {

	return &Email{
		To:      to,
		Title:   title,
		Content: content,
	}
}

func (s *MailService) SendEmail(email *Email) {

	go (func(s *MailService) {

		host := strings.Split(s.Host, ":")[0]
		to := strings.Join(email.To, ";")

		// msg := fmt.Sprintf("From: %s{[}]To: %s{[}]Subject: %s{[}]%s{[}]{[}]", s.Email, to, email.Title, email.Content)
		// msg = strings.Replace(msg, "{[}]", "\r\n", -1)

		msg := fmt.Sprintf("From: %s{[}]To: %s{[}]Subject: %s{[}]Content-Type: text/html; {[}]charset=\"gb-18030\" {[}]{[}]%s", s.Email, to, email.Title, email.Content)
		msg = strings.Replace(msg, "{[}]", "\r\n", -1)

		err := smtp.SendMail(
			s.Host,
			smtp.PlainAuth("", s.Account, s.Password, host),
			s.Email,
			email.To,
			[]byte(msg),
		)

		if err != nil {
			log.Fatal(err)
		}

	})(s)
}
